package org.springframework.samples.petclinic.repository.jpa;

import java.util.Collection;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.samples.petclinic.model.Alien;
import org.springframework.samples.petclinic.model.Owner;
import org.springframework.samples.petclinic.repository.AlienRepository;
import org.springframework.stereotype.Repository;

@Repository
public class JpaAlienRepositoryImpl implements AlienRepository {

    @PersistenceContext
    private EntityManager em;
    private static Logger logger = LoggerFactory.getLogger(JpaAlienRepositoryImpl.class);
    
    @SuppressWarnings("unchecked")
    public Collection<Alien> findByLastName(String lastName) {
        // using 'join fetch' because a single query should load both owners and pets
        // using 'left join fetch' because it might happen that an owner does not have pets yet
        Query query = this.em.createQuery("SELECT DISTINCT alien FROM Alien alien WHERE alien.lastName LIKE :lastName");
        query.setParameter("lastName", lastName + "%");
        return query.getResultList();
    }

	@Override
	public Alien findById(int id) throws DataAccessException {
        Query query = this.em.createQuery("SELECT alien FROM Alien alien alien.id =:id");
        query.setParameter("id", id);
        return (Alien) query.getSingleResult();
	}

	
	public void saveSingle(Alien alien) throws DataAccessException {
    	if (alien.getId() == null) {
    	    logger.info("save alien");
    		this.em.persist(alien);     	
    	}
    	else {
    		this.em.merge(alien);    
    	}


	}
	
	@Override
	public void save(Alien alien) throws DataAccessException {
        if (alien.getId() == null) {
            logger.info("save alien series start");
            for (int i=0; i < alien.getSeriesSize(); i++) {
                logger.info("save alien pos " + i);
                alien.setInsertDate(new DateTime());
                
                alien.setSeriesPos(i);
                
                this.em.persist(alien);
                if (alien.getAfterInsertSleep() > 0) {
                    try {
                        Thread.sleep(alien.getAfterInsertSleep());
                    } catch (InterruptedException e) {
                        logger.error("blad: ", e);
                    }
                }
                alien = (Alien) alien.clone();
                alien.setId(null);
            }
            logger.info("save alien series end");
        }
        else {
            this.em.merge(alien);    
        }
	}

}
